// 云函数入口文件
const cloud = require('wx-server-sdk')
const mysql = require('mysql2/promise')

cloud.init({
  env: 'uniapp-8g0lywngd57d5c18'
})

// MySQL连接配置
const config = {
  host: 'sh-cynosdbmysql-grp-b4b8nkho.sql.tencentcdb.com',
  port: 25932,
  database: 'custom_order_management',
  user: 'root',
  password: 'jQ6w2uwY',
  // 添加连接选项
  connectTimeout: 10000, // 连接超时时间10秒
  connectionLimit: 10,   // 连接池限制
  waitForConnections: true,
  queueLimit: 0
}

// 云函数入口函数
exports.main = async (event, context) => {
  const { inviteCode, studentId } = event
  const wxContext = cloud.getWXContext()

  let connection
  try {
    // 创建数据库连接
    connection = await mysql.createConnection(config)
    await connection.beginTransaction()

    // 查找邀请码对应的班级
    const [classes] = await connection.execute(
      'SELECT * FROM class_info WHERE invite_code = ?',
      [inviteCode]
    )

    if (classes.length === 0) {
      throw new Error('邀请码无效')
    }

    const classInfo = classes[0]

    // 检查学号是否在班级名单中
    const [students] = await connection.execute(
      'SELECT * FROM student_list WHERE class_id = ? AND student_id = ?',
      [classInfo.class_id, studentId]
    )

    if (students.length === 0) {
      throw new Error('学号不在班级名单中')
    }

    // 更新用户信息
    await connection.execute(
      'UPDATE member SET student_id = ?, class_id = ? WHERE openid = ?',
      [studentId, classInfo.class_id, wxContext.OPENID]
    )

    // 提交事务
    await connection.commit()

    return {
      success: true,
      classId: classInfo.class_id
    }

  } catch (error) {
    if (connection) {
      await connection.rollback()
    }
    console.error('验证邀请码失败:', error)
    return {
      error: error.message || '验证失败，请重试'
    }
  } finally {
    if (connection) {
      await connection.end()
    }
  }
} 